import { type RouteRecordRaw, createRouter, createWebHistory } from 'vue-router';
import { prefixPathRoutes, unfoldRoutes } from './router-util';
import { getLayoutRoutesList } from './layout/layout';
console.log('==========route', unfoldRoutes(prefixPathRoutes(getLayoutRoutesList())));
/**
 * 创建路由
 */
export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: unfoldRoutes(prefixPathRoutes(getLayoutRoutesList())),
});

/**
 * 得到所有根页面路径 如['/login', '/err403', '/err404']
 */
export function getRootRoutes(routes?: RouteRecordRaw[]): string[] {
  const newRoutes = routes || router.options.routes.filter((item) => item.path !== '/' && !item.redirect);
  let paths: string[] = [];
  newRoutes.forEach((item) => {
    paths.push(item.path);
    if (item.children) {
      paths = paths.concat(getRootRoutes(item.children));
    }
  });
  return paths;
}

/**
 * 在测试环境下检测路由的合规性
 */
if (import.meta.env.DEV) {
  /** 原始配置表 子路由合规性验证 */
  const _childrenPathVerify = (_router: RouteRecordRaw[], isChild: boolean) => {
    _router.forEach((route) => {
      const path = route.path || '';
      isChild && path.includes('/') && console.warn(`${path}子路由路径不能包含/`);
      // 如果有下级就递归调用
      route.children && Array.isArray(route.children) && _childrenPathVerify(route.children, true);
    });
  };
  _childrenPathVerify(getLayoutRoutesList(), false);
  const lastPathObj: Record<string, boolean> = {};
  const nameObj: Record<string, boolean> = {};
  const titleObj: Record<string, boolean> = {};
  const _routerComplianceDetection = (_router: Readonly<RouteRecordRaw[]>) => {
    _router.forEach((route: RouteRecordRaw) => {
      const path = route.path || '';
      const name = (route.name || '') as string;
      !path && console.warn('路由的path字段不能为空');
      !route.component && name && console.warn(`${path}没有component的路由不能包含name字段`);
      route.component && !name && !route.redirect && console.warn(`${path}有component的路由必须包含name字段`);
      path !== '/:pathMatch(.*)*' && path.toLowerCase() !== path && console.warn(`${path}路由的path字段包含大写,建议统一改为小写`);
      name.toLowerCase() !== name && console.warn(`${path}路由的name字段包含大写,建议统一改为小写`);

      if (!route.redirect) {
        const title = route.meta && route.meta.title ? route.meta.title : '';
        const lastPath = path.split('/').pop() || '';
        lastPath !== name && console.warn(`${path}路径结尾和name不匹配`);
        lastPathObj[lastPath] && console.warn(`${path}路由的path字段有重复`);
        lastPathObj[lastPath] = true;
        nameObj[name] && console.warn(`${path}路由的name字段有重复`);
        nameObj[name] = true;
        if (!title) {
          console.warn(`${path}路由配置缺少meta.title字段`);
        } else {
          titleObj[title] && console.warn(`${path}路由的meta.title字段有重复`);
          titleObj[title] = true;
        }
      } else {
        !String(route.redirect).startsWith('/') && console.warn(`${path}重定向路径必须以/开头`);
      }
      if (route.children) {
        // 如果有下级就递归调用
        Array.isArray(route.children) && _routerComplianceDetection(route.children);
      } else {
        path.includes('/operation/') && route?.meta?.noCache && console.warn(`${route.path}订单相关路由meta.noCache必须设置为false`);
        path.includes('/query/') && route?.meta?.noCache && console.warn(`${route.path}查询相关路由meta.noCache必须设置为false`);
      }
    });
  };
  router.options.routes.forEach((route) => {
    !route.path.startsWith('/') && console.warn(`${route.path}顶级路由的路径必须/开头`);
    !route.component && !route.redirect && console.warn(`${route.path}顶级路由必须有有component`);
    !route?.meta?.hidden && !route.redirect && console.warn(`${route.path}顶级路由meta.hidden必须设置为true`);
    !route?.meta?.noCache && !route.redirect && console.warn(`${route.path}顶级路由meta.noCache必须设置为true`);
  });
  _routerComplianceDetection(router.options.routes);
}
export default router;
